<?php

namespace App\Handlers;

use HuaweiCloud\SDK\Core\Auth\BasicCredentials;
use HuaweiCloud\SDK\Core\Http\HttpConfig;
use HuaweiCloud\SDK\Core\Exceptions\ConnectionException;
use HuaweiCloud\SDK\Core\Exceptions\RequestTimeoutException;
use HuaweiCloud\SDK\Core\Exceptions\ServiceResponseException;
use HuaweiCloud\SDK\IoTDA\V5\IoTDAClient;
use HuaweiCloud\SDK\IoTDA\V5\Model\ListDevicesRequest;
use Illuminate\Support\Facades\Redis;

// use Illuminate\Support\Facades\Cache;
// use Illuminate\Support\Facades\Redis;
// use Salman\Mqtt\MqttClass\Mqtt;
// use App\Models\Device;
// use App\Models\SwitchData;
// use App\Models\BatteryConfig;

class HuaweiCloudHandler
{
    const AK = 'SQZRADNU46PFRRDDZQEQ';
    const SK = 'LhmSkpbyAkrzpGjUS3rkxgrWPu22zXT7VBNMVtVH';
    const ENDPOINT = 'https://a15fa5262c.iotda.cn-north-4.myhuaweicloud.com';
    const PROJECTID = '0a36ab58d90025c02f61c00724d38a9b';
    const DEVICEID = '61b7f6902b2aa20288bbbbd7_Battery_monitor_01';

    public static function getDeviceInfo(){
        $infoKey = "huawei_info";
        $info = Redis::get($tokenKey);
        if ($info) {
            return json_decode($info, true);
        } else {
            $credentials = new BasicCredentials(self::AK, self::SK, self::PROJECTID);
            // 创建IoTDAClient实例并初始化
            $client = IoTDAClient::newBuilder(new IoTDAClient)
              ->withEndpoint(self::ENDPOINT)
              ->withCredentials($credentials)
              ->build();
            // 实例化请求对象
            $request = new ListDevicesRequest();
            try {
              // 调用查询设备列表接口
              $response = $client->ListDevices($request);
            } catch (ConnectionException $e) {
              $msg = $e->getMessage();
              echo "\n". $msg ."\n";
            } catch (RequestTimeoutException $e) {
              $msg = $e->getMessage();
              echo "\n". $msg ."\n";
            } catch (ServiceResponseException $e) {
              echo "\n";
              echo $e->getHttpStatusCode(). "\n";
              echo $e->getErrorCode() . "\n";
              echo $e->getErrorMsg() . "\n";
            }
            $res = json_decode($response, true);
            foreach ($res as $one) {
                if ($one['device_id'] == self::DEVICEID) {
                    Redis::set($tokenKey, json_encode($one));
                    return $one;
                }
            }
        }
    }

    public static function getAuth(){
        $username = "hw38854930";
        $password = "hc5922497";
        $domainName = "hw38854930";
        $projectName = "cn-north-4";

        $authQuery = '{"auth":{"identity":{"methods":["password"],"password":{"user":{"name":"'.$username.'","password":"'.$password.'","domain":{"name":"'.$domainName.'"}}}},"scope":{"project":{"name":"'.$projectName.'"}}}}';

        $tokenKey = "huawei_token";
        $token = Redis::get($tokenKey);
        if (empty($token)) {
            $url = 'https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens';
            $header = self::_getTokenCurl($url, $authQuery);
            if (strpos($header, 'X-Subject-Token') !== false) {
                $headerArr = explode("\r\n", $header);
                foreach ($headerArr as $one) {
                    if (strpos($one, 'X-Subject-Token') !== false) {
                        $token = trim( substr($one, strlen('X-Subject-Token')+1) );
                    }
                }
            }
            Redis::setex($tokenKey , 3600*24 , $token);
        }
        return $token;
    }

    public static function getMessage(){
        $token = self::getAuth();
        $url = self::ENDPOINT."/v5/iot/".self::PROJECTID."/devices/".self::DEVICEID."/messages";
        $header[] = "X-Auth-Token: ".$token;

        $res = self::_getMessageCurl($url, $header);
        $res = json_decode($res, true);
    }

    public static function getRuleList(){
        $token = self::getAuth();
        $url = self::ENDPOINT."/v5/iot/".self::PROJECTID."/routing-rule/rules";
        $header[] = "X-Auth-Token: ".$token;
        $res = self::_getMessageCurl($url, $header);
        $res = json_decode($res, true);
    }

    public static function addOneRule(){
        $token = self::getAuth();
        $url = self::ENDPOINT."/v5/iot/".self::PROJECTID."/routing-rule/rules";
        $header[] = "X-Auth-Token: ".$token;

        $params['rule_name'] = "php-test";
        $params['description'] = "php-test";
        $params['subject']['resource'] = "device.message";
        $params['subject']['event'] = "report";
        $params['app_type'] = "APP";
        $params['app_id'] = "98381ab7cf444a28a119dceea1443f60";
        $res = self::_postCurl($url, json_encode($params), $header);
        $res = json_decode($res, true);
    }

    public static function delOneRule(){

    }

    public static function addOneRuleAction(){
        $url = self::ENDPOINT."/v5/iot/".self::PROJECTID."/routing-rule/actions";
        $token = self::getAuth();
        $header[] = "X-Auth-Token: ".$token;
        $params['rule_id'] = '84706032-e239-4bfc-8feb-0970fc93bd35';
        $params['channel'] = 'HTTP_FORWARDING';
        $params['channel_detail']['http_forwarding']['url'] = 'http://yun.xmcitypower.com/api/huaweiCallback';
        $res = self::_postCurl($url, json_encode($params), $header);
        $res = json_decode($res, true);
    }

    public static function getRuleActionList(){
        $url = self::ENDPOINT."/v5/iot/".self::PROJECTID."/routing-rule/actions";
        $token = self::getAuth();
        $header[] = "X-Auth-Token: ".$token;
        $res = self::_getMessageCurl($url, $header);
        $res = json_decode($res, true);
    }


    public static function _getTokenCurl($url, $params){
        $ch = curl_init();
        $header[] = "Content-Type: application/json";
        $user_agent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36";
        curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_NOBODY, true);
        curl_setopt($ch, CURLOPT_USERAGENT,$user_agent);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

        $content = curl_exec($ch);
        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $header = substr($content, 0, $headerSize);
        curl_close($ch);
        return $header;

    }

    public static function _getMessageCurl($url, $eheader){
        $ch = curl_init();
        $header[] = "Content-Type: application/json";
        $header = array_merge($header, $eheader);

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }

    public static function _postCurl($url, $params, $eheader){
        $ch = curl_init();
        $header[] = "Content-Type: application/json";
        $header = array_merge($header, $eheader);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }
}